package com.github.iot.activity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.DialogFragment;

import com.github.iot.R;
import com.github.iot.adapter.ShowroomAdapter;
import com.github.iot.dao.CommonDaoUtils;
import com.github.iot.dao.DaoUtilsStore;
import com.github.iot.entity.Showcase;
import com.github.iot.entity.Showroom;
import com.github.iot.entity.User;
import com.github.iot.entity.UserToken;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.BarUtils;
import com.github.iot.utils.DateUtils;
import com.github.iot.utils.FastJsonUtils;
import com.github.iot.utils.SharedPreferencesUtils;
import com.github.iot.utils.ToastUtils;
import com.github.iot.view.LineGridView;
import com.github.iot.view.RxTitle;
import com.github.iot.view.dialogs.fragment.SimpleDialogFragment;
import com.github.iot.view.dialogs.iface.ISimpleDialogListener;
import com.github.iot.view.loaddatalayout.LoadDataLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.mylhyl.circledialog.CircleDialog;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 首页Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/06 9:14
 * @Version: v1.0.0
 */
public class MainActivity extends AppCompatActivity implements ISimpleDialogListener {

    private long firstTime = 0;
    private static final int REQUEST_SIMPLE_DIALOG = 42;
    private static final int REQUEST_OPTION_DIALOG = 43;
    private static final int REQUEST_DELETE_DIALOG = 44;

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawer;

    @BindView(R.id.rx_title)
    RxTitle mTitle;

    @BindView(R.id.loadDataLayout)
    LoadDataLayout mLoadDataLayout;

    @BindView(R.id.fab)
    FloatingActionButton mFab;

    @BindView(R.id.nav_view)
    NavigationView mNavigationView;

    @BindView(R.id.gv_lanuch_start)
    LineGridView mGridView;

    private String[] icons = new String[]{"app_wdrw_ico", "app_wdzj_ico", "app_wdjh_ico", "all_big_ico", "app_jhsp_ico", "app_jxpd_ico", "app_lccy_ico", "app_lcsp_ico"};
    private List<Showroom> mDatas;
    private ShowroomAdapter mAdapter;
    private DialogFragment mDialog1;
    private DialogFragment mDialog2;
    private static boolean flag = true;

    private CommonDaoUtils<Showroom> showroomDaoUtils = DaoUtilsStore.getInstance().getShowroomDaoUtils();
    private CommonDaoUtils<Showcase> showcaseDaoUtils = DaoUtilsStore.getInstance().getShowcaseDaoUtils();
    private CommonDaoUtils<UserToken> userTokenDaoUtils = DaoUtilsStore.getInstance().getUserTokenDaoUtils();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarColor(this, R.color.colorPrimaryDark);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);

        initView();
        initNavigation();
        initData();

        if (!UsbFeatureSupported()) {
            ToastUtils.info("系统不支持USB Host功能");
            System.exit(0);
            return;
        }
    }

    /**
     * Navigation 点击监听事件
     */
    private void initNavigation() {
        mNavigationView.setNavigationItemSelectedListener(menuItem -> {
            switch (menuItem.getItemId()) {
                case R.id.nav_user_info:
                    ActivityUtils.skipActivity(MainActivity.this, UserInfoActivity.class);
                    break;
                case R.id.nav_net_setting:
                    ActivityUtils.skipActivity(MainActivity.this, NetSettingActivity.class);
                    break;
                case R.id.nav_door_command:
                    ActivityUtils.skipActivity(MainActivity.this, DoorCommandActivity.class);
                    break;
                case R.id.nav_token:
                    ActivityUtils.skipActivity(MainActivity.this, UserTokenActivity.class);
                    break;
                case R.id.nav_user_list:
                    ActivityUtils.skipActivity(MainActivity.this, UserListActivity.class);
                    break;
                case R.id.nav_clear:
                    ToastUtils.success("缓存已清除");
                    break;
                case R.id.nav_exit:
                    SimpleDialogFragment.createBuilder(MainActivity.this, getSupportFragmentManager())
                            .setTitle("系统提示")
                            .setMessage("您确定要退出吗？")
                            .setPositiveButtonText("确定")
                            .setCancelable(false)
                            .setNegativeButtonText("取消")
                            .setRequestCode(REQUEST_SIMPLE_DIALOG)
                            .show();
                    break;
                default:

                    break;
            }
            mDrawer.closeDrawers();
            return false;
        });
    }

    @OnClick({R.id.fab, R.id.iv_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fab:
                addShowroom();
                break;
            case R.id.iv_left:
                mDrawer.openDrawer(GravityCompat.START);
                break;
            default:

                break;
        }
    }

    private void initView() {
        mGridView.setFocusable(false);
        mGridView.setOnItemClickListener((parent, view, position, id) -> {
            if (flag) {
                flag = false;
                Showroom showroom = mDatas.get(position);
                Bundle bundle = new Bundle();
                bundle.putString("showroom", FastJsonUtils.obj2JsonStr(showroom));
                ActivityUtils.skipActivity(MainActivity.this, ShowroomActivity.class, bundle);
            }
        });

        mGridView.setOnItemLongClickListener((parent, view, position, id) -> {
            Showroom showroom = mDatas.get(position);
            mDialog1 = SimpleDialogFragment.createBuilder(MainActivity.this, getSupportFragmentManager())
                    .setTitle("系统提示")
                    .setMessage("请选择您操作步骤")
                    .setCancelable(false)
                    .setPositiveButtonText("取消")
                    .setNegativeButtonText("修改")
                    .setNeutralButtonText("删除")
                    .setTag(FastJsonUtils.obj2JsonStr(showroom))
                    .setRequestCode(REQUEST_OPTION_DIALOG)
                    .show();

            return true;
        });

        mTitle.setRightTextOnClickListener(v -> ActivityUtils.skipActivity(MainActivity.this, ShowroomManageActivity.class));

        View headerView = mNavigationView.getHeaderView(0);
        Menu menu = mNavigationView.getMenu();

        TextView mNickname = headerView.findViewById(R.id.tv_nickname);
        TextView mUsername = headerView.findViewById(R.id.tv_username);
        TextView mType = headerView.findViewById(R.id.tv_type);

        String str = SharedPreferencesUtils.getString(this, "iot_login_user", null);
        if (null != str) {
            User user = FastJsonUtils.strToBean(str, User.class);
            mNickname.setText(user.getNickname());
            mUsername.setText(user.getUsername());

            if (1 == user.getType()) {
                menu.findItem(R.id.nav_net_setting).setVisible(true);
                menu.findItem(R.id.nav_user_list).setVisible(true);
                menu.findItem(R.id.nav_door_command).setVisible(true);
                menu.findItem(R.id.nav_token).setVisible(true);
                mType.setText("超级管理员");
            } else if (2 == user.getType()) {
                menu.findItem(R.id.nav_net_setting).setVisible(true);
                menu.findItem(R.id.nav_user_list).setVisible(true);
                menu.findItem(R.id.nav_door_command).setVisible(true);
                menu.findItem(R.id.nav_token).setVisible(true);
                mType.setText("管理员");
            } else if (3 == user.getType()) {
                menu.findItem(R.id.nav_net_setting).setVisible(false);
                menu.findItem(R.id.nav_user_list).setVisible(false);
                menu.findItem(R.id.nav_door_command).setVisible(false);
                menu.findItem(R.id.nav_token).setVisible(false);
                mType.setText("普通用户");
            }
        }

        mLoadDataLayout.getEmptyView().setOnClickListener(v -> addShowroom());
    }

    /**
     * 初始化数据
     */
    private void initData() {
        flag = true;
        mLoadDataLayout.setStatus(LoadDataLayout.LOADING);
        Observable.timer(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(t -> getData());
    }

    private void getData() {
        String sql = "ORDER BY _id ASC";
        mDatas = showroomDaoUtils.queryByNativeSql(sql, null);
        for (int i = 0; i < mDatas.size(); i++) {
            Showroom showroom = mDatas.get(i);
            List<Showcase> lists = showcaseDaoUtils.queryByNativeSql("where SHOWROOM_ID = ?", new String[]{String.valueOf(showroom.getId())});
            showroom.setNum(lists.size());
        }

        if (mDatas.size() > 0) {
            mLoadDataLayout.setStatus(LoadDataLayout.SUCCESS);
            mAdapter = new ShowroomAdapter(MainActivity.this, mDatas);
            mGridView.setAdapter(mAdapter);
        } else {
            mLoadDataLayout.setStatus(LoadDataLayout.EMPTY);
        }
    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {
        // 修改
        if (requestCode == REQUEST_OPTION_DIALOG) {
            if (null != mDialog1) {
                String tag = mDialog1.getTag();
                Showroom showroom = FastJsonUtils.strToBean(tag, Showroom.class);
                updateShowroom(showroom);
            }
        }
    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {
        // 删除
        if (requestCode == REQUEST_OPTION_DIALOG) {
            if (null != mDialog1) {
                String tag = mDialog1.getTag();
                Showroom showroom = FastJsonUtils.strToBean(tag, Showroom.class);
                mDialog2 = SimpleDialogFragment.createBuilder(MainActivity.this, getSupportFragmentManager())
                        .setTitle("系统提示")
                        .setMessage("您确定要删除[" + showroom.getTitle() + "]吗？")
                        .setCancelable(false)
                        .setTag(tag)
                        .setPositiveButtonText("确定")
                        .setNegativeButtonText("取消")
                        .setRequestCode(REQUEST_DELETE_DIALOG)
                        .show();
            }
        }
    }

    @Override
    public void onPositiveButtonClicked(int requestCode) {
        if (requestCode == REQUEST_SIMPLE_DIALOG) {
            SharedPreferencesUtils.remove(MainActivity.this, "iot_login_user");
            ActivityUtils.skipActivityAndFinishAll(MainActivity.this, LoginActivity.class);
        }

        // 删除
        if (requestCode == REQUEST_DELETE_DIALOG) {
            if (null != mDialog2) {
                String tag = mDialog2.getTag();
                if (null != tag) {
                    Showroom showroom = FastJsonUtils.strToBean(tag, Showroom.class);
                    deleteShowroom(showroom);
                }
            }
        }
    }

    /**
     * 修改展厅
     *
     * @param showroom
     */
    private void updateShowroom(Showroom showroom) {
        new CircleDialog.Builder()
                .setCanceledOnTouchOutside(false)
                .setCancelable(true)
                .setTitle("修改展厅")
                .setInputHint("请输入展厅名称")
                .setInputText(showroom.getTitle())
                .setInputHeight(90)
                .setInputShowKeyboard(true)
                .setInputEmoji(true)
                .setInputCounter(10)
                .setCancelable(false)
                .configInput(params -> params.styleText = Typeface.BOLD)
                .setNegative("取消", null)
                .setPositiveInput("确定", (text, v) -> {
                    if (TextUtils.isEmpty(text)) {
                        ToastUtils.warning("请输入展厅名称");
                        return false;
                    } else {
                        showroom.setTitle(text);
                        boolean flag = showroomDaoUtils.update(showroom);
                        if (flag) {
                            ToastUtils.success("操作成功");
                            initData();
                        } else {
                            ToastUtils.error("操作失败");
                        }
                        return true;
                    }
                })
                .show(getSupportFragmentManager());
    }

    /**
     * 删除展厅
     *
     * @param showroom
     */
    private void deleteShowroom(Showroom showroom) {
        boolean flag = showroomDaoUtils.delete(showroom);
        if (flag) {
            String sql = "where SHOWROOM_ID = ?";
            String[] conditions = new String[]{String.valueOf(showroom.getId())};
            List<Showcase> list = showcaseDaoUtils.queryByNativeSql(sql, conditions);
            for (Showcase showcase : list) {
                showcaseDaoUtils.delete(showcase);
            }
            initData();
            ToastUtils.success("操作成功");
        } else {
            ToastUtils.error("操作失败！");
        }
    }

    /**
     * 添加展厅
     */
    private void addShowroom() {
        new CircleDialog.Builder()
                .setCanceledOnTouchOutside(false)
                .setCancelable(true)
                .setTitle("添加展厅")
                .setInputHint("请输入展厅名称")
                .setInputHeight(90)
                .setInputShowKeyboard(true)
                .setInputEmoji(true)
                .setInputCounter(30)
                .setCancelable(false)
                .configInput(params -> params.styleText = Typeface.BOLD)
                .setNegative("取消", null)
                .setPositiveInput("确定", (text, v) -> {
                    if (TextUtils.isEmpty(text)) {
                        ToastUtils.warning("请输入展厅名称");
                        return false;
                    } else {
                        addShowroom(text);
                        return true;
                    }
                })
                .show(getSupportFragmentManager());
    }

    /**
     * 添加展厅
     *
     * @param title
     */
    private void addShowroom(String title) {
        Showroom showroom = new Showroom();
        showroom.setTitle(title);
        showroom.setNum(0);
        showroom.setSort(mDatas.size());
        showroom.setIco(icons[new Random().nextInt(icons.length)]);
        showroomDaoUtils.insert(showroom);

        initData();
    }

    /**
     * 检查授权
     */
    private void checkToken() {
        //userTokenDaoUtils.deleteAll();
        List<UserToken> list = userTokenDaoUtils.queryAll();
        if (list.size() > 0) {
            UserToken userToken = list.get(0);
            Date nowDate = DateUtils.getNow();
            Date expireDate = DateUtils.string2Date(userToken.getDate(), DateUtils.YMD_FORMAT);
            if (expireDate.before(nowDate)) {
                Bundle bundle = new Bundle();
                bundle.putString("token", FastJsonUtils.obj2JsonStr(userToken));
                ActivityUtils.skipActivityAndFinish(MainActivity.this, TokenActivity.class, bundle);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        checkToken();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 2000) {
                System.exit(0);
            } else {
                Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 系统是否支持USB Host功能
     *
     * @return true:系统支持USB Host false:系统不支持USB Host
     */
    public boolean UsbFeatureSupported() {
        return this.getPackageManager().hasSystemFeature("android.hardware.usb.host");
    }

}